package com.demo.index;

import com.demo.common.model.LoginLog;
import com.demo.common.model.User;
import com.demo.common.util.StringUtil;
import com.demo.user.UserService;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;

import javax.servlet.http.HttpSession;

public class LoginController extends Controller {

    @Inject
    UserService service;

    @Inject
    LoingLogService logService;

    //加载登录页面
    public void index() {
        render("login.html");
    }

    //登录系统
    public void login(){
        String username=getPara("username");
        String password=getPara("password");
        User user=service.findFirstByUserNameAndPassword(username,password);
        if(user!=null) {
            user.setOnline(1);
            user.update();
            LoginLog loginLog=new LoginLog();
            loginLog.setName(username);
            loginLog.setCreatedate(StringUtil.strToTimeStamp());
            loginLog.save();
            setSessionAttr("fangweiliang",logService.findCount());
            setSessionAttr("online",service.findCountByOnline("1"));
            setSessionAttr("loginUser",user);
            setAttr("result",1);
        }else{
            setAttr("result",2);
        }
        renderJson();
    }

    //退出系统
    public void logout(){
        User user=(User)getSessionAttr("loginUser");
        user.setOnline(0);
        user.update();
        HttpSession session=getSession();
        session.removeAttribute("fangweiliang");
        session.removeAttribute("online");
        session.removeAttribute("loginUser");
//        setSessionAttr("loginUser",null);
//        setSessionAttr("online",null);
//        setSessionAttr("fangweiliang",null);
        redirect("/");
    }
}
